package com.xyzwps.lib.json.element;

public record JsonString(String value) implements JsonElement {

    @Override
    public String toString() {
        return this.stringify();
    }

    public static String unescape(String s) {
        if (s == null) return null;

        var sb = new StringBuilder();
        s.chars().forEachOrdered(it -> {
            char c = (char) it;
            switch (c) {
                case '\\':
                    sb.append("\\\\");
                    break;
                case '"':
                    sb.append("\\\"");
                    break;
                case '\b':
                    sb.append("\\b");
                    break;
                case '\f':
                    sb.append("\\f");
                    break;
                case '\n':
                    sb.append("\\n");
                    break;
                case '\r':
                    sb.append("\\r");
                    break;
                case '\t':
                    sb.append("\\t");
                    break;
                default:
                    sb.append(c);
            }
        });
        return sb.toString();
    }

    public String toUnescapedString() {
        return unescape(this.value);
    }

    @Override
    public <R> R visit(JsonElementVisitor<R> visitor) {
        return visitor.visit(this);
    }

    @Override
    public <R, C> R visit(C ctx, JsonElementVisitor2<R, C> visitor) {
        return visitor.visit(ctx, this);
    }
}
